/******************************************************************************
 **
 **    LISA Confidential
 **
 **    Source Materials
 **
 **    (C) COPYRIGHT LISA 2008-2009
 **
 **
 **  File Name:      GetPooledTaskInstancesCommand.java
 **  Description:
 **  Date:           2008-10-28
 **  Author:         LisaQian
 ******************************************************************************/
package com.ti.andon.workflow.command;

import java.util.Iterator;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jbpm.JbpmContext;
import org.jbpm.command.Command;
import org.jbpm.db.TaskMgmtSession;
import org.jbpm.graph.exe.ProcessInstance;
import org.jbpm.taskmgmt.exe.TaskInstance;

public class GetPooledTaskInstanceCmd implements Command
{
	private static Log logger = LogFactory.getLog(GetPooledTaskInstanceCmd.class);
	
	Long pooledActorId;

	String businessKey;

	String processDefinition;

	String taskName;

	/**
	 * Serial Version ID.
	 */
	private static final long serialVersionUID = 7370288897944799402L;

	public GetPooledTaskInstanceCmd(Long pooledActorId, String businessKey, String processDefinition,
			String taskName)
	{
		this.pooledActorId = pooledActorId;
		this.businessKey = businessKey;
		this.processDefinition = processDefinition;
		this.taskName = taskName;

	}

	/**
	 * Retrieves the first pooled task instance matches the actor, the process
	 * definition name, business key and task name.
	 * 
	 * @param jbpmContext
	 * @return the first pooled task instance matches the actor, the process
	 *         definition name, business key and task name.
	 */
	public Object execute(JbpmContext jbpmContext) throws Exception
	{
		if (null != pooledActorId)
		{
			TaskMgmtSession taskMgmtSession = jbpmContext.getTaskMgmtSession();
			List pooledTasklist = taskMgmtSession.findPooledTaskInstances(pooledActorId.toString());
			TaskInstance taskInstance = null;
			if (null != pooledTasklist && pooledTasklist.size() > 0)
			{
				Iterator iterPooledTaskInstance = pooledTasklist.iterator();
				while (iterPooledTaskInstance.hasNext())
				{
					taskInstance = (TaskInstance) iterPooledTaskInstance.next();
					ProcessInstance pi = taskInstance.getProcessInstance();
					if (null != pi && null != pi.getProcessDefinition() && null != pi.getProcessDefinition().getName()
							&& pi.getProcessDefinition().getName().equals(processDefinition) && null != pi.getKey()
							&& null != businessKey && pi.getKey().equals(businessKey)
							&& taskInstance.getName().equals(taskName))
					{
						break;
					}
				}
			}
			return taskInstance;
		}
		else
		{
			logger.error("GetPooledTaskInstanceCmd.execute() : pooledActorId can not be null!!!");
			return null;
		}
	}

}
